package com.sgcc.fj.pmos.common.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public class SignUtils {

    public static String sortParams(Map<String, Object> param) {
        String[] keys = param.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        ArrayList<String> params = new ArrayList<>();
        for (String k : keys) {
            Object v = param.get(k);
            params.add(k + "=" + v);
        }
        return join(params.toArray(new String[0]), "&");
    }

    private static String join(final Object[] array, final String separator) {
        if (array == null) {
            return null;
        }
        return join(array, separator, 0, array.length);
    }

    private static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
        if (array == null) {
            return null;
        }
        if (separator == null) {
            separator = "";
        }
        final int noOfItems = endIndex - startIndex;
        if (noOfItems <= 0) {
            return "";
        }
        final StringBuilder buf = newStringBuilder(noOfItems);
        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

    private static StringBuilder newStringBuilder(final int noOfItems) {
        return new StringBuilder(noOfItems * 16);
    }


}
